package se.psytrance;

import java.util.Vector;

import se.psytrance.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
/**
 * Yeah, there is almoste no documentation at all :), I didnt find any time did I? Code
 * is so ugly I guess you dont wanna have a look.
 * @author Joynes
 *
 */
public class SleepWithSwedishHumour extends Activity {
	private static final int TIME_BUTTON_INTERVAL = 5;

	/** Called when the activity is first created. */

	static int speed = 1;
	
	static TextView text;
	static TextView artistName;
	static int counterMinutes = 40;
	static int counterSeconds = 59;
	static int index = 0;
	
	ProgressDialog dialog;
	
	
	static Vector<Episode> episodes;

	MediaController nc;
	VideoView player;
	
	AlertDialog alert;

	enum State {
		ZERO, COUNTING, NULL
	};

	State state = State.NULL;

	private Handler mHandler = new Handler();

	public static final String PREFS_NAME = "SleepWithSwedishHumour";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		episodes = new EpisodeFactory().getEpisodes();

		// Restore the index
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		index = settings.getInt("index", 0);
		
		//int position = settings.getInt("position", 0);
		
		Log.e("data", "Retrieving index from db: " + index);

		text = (TextView) findViewById(R.id.TextView01);
		
		artistName = (TextView) findViewById(R.id.TextView02);

		Button button = (Button) findViewById(R.id.Button02);

		// Increase the counter
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Log.e("test", "The counter is " + counterMinutes);
				// Maybe start the counter again
				if (state == State.ZERO) {
					state = State.COUNTING;
					postDelayed();
					
					player.start();
				}

				counterMinutes += TIME_BUTTON_INTERVAL;

				printCounter();

			}
		});

		button = (Button) findViewById(R.id.Button01);

		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				counterMinutes -= TIME_BUTTON_INTERVAL;

				printCounter();

			}
		});

		player = (VideoView) findViewById(R.id.VideoView01);

		nc = new MediaControllerCustom(this);
		
		player.setMediaController(nc);
		player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer arg0) {
				Log.e("test", "Song completed");
				index++;
				if (index >= episodes.size()) {
					index = 0;
				}
				loadSong(episodes.elementAt(index));

			}
		});
		
		// Remove the loading bar when loading the channel is complete
		
		player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
			
			@Override
			public void onPrepared(MediaPlayer arg0) {
				dialog.cancel();
				
			}
		});
		
		// have my own erroListener
		
		player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
			
			@Override
			public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
				dialog.cancel();
				
				AlertDialog.Builder builder = new AlertDialog.Builder(SleepWithSwedishHumour.this);
				builder.setMessage("Problem: You might need a more reliably internet connection. Click ok to exit application and try restart!")
				       .setCancelable(false)
				       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   SleepWithSwedishHumour.this.finish();
				           }
				       })
				       ;
				alert = builder.create();
				
				alert.show();
				
				return true;
			}
		});

		loadSong(episodes.elementAt(index));
		//Log.e("dsfsd", "Seeking to position " + position);
		//player.seekTo(position);
		
		state = State.COUNTING;
		mHandler.removeCallbacks(mUpdateTimeTask);
		postDelayed();
		
		printCounter();
	}
	
	private void postDelayed() {
		
		mHandler.postDelayed(mUpdateTimeTask, 1000);
	}

	private void loadSong(Episode episode) {
		player.setVideoPath(episode.path);
		player.requestFocus();
		player.start();

		// also update info about the artist
		artistName.setText(episode.name);

		Log.e("test", "Loading song " + episode.name);
		
		dialog = ProgressDialog.show(this, "", 
                "Loading show " + episode.name, true);
	}

	private void printCounter() {

		if (counterSeconds < 0) {
			counterSeconds = 59;
			counterMinutes -= speed;
		}

		if (counterMinutes < 0) {
			state = State.ZERO;
			counterSeconds = 0;
			counterMinutes = 0;
			// player.stopPlayback();
			player.pause();
		}

		String minutesText = String.valueOf(counterMinutes);
		String secondsText = String.valueOf(counterSeconds);

		if (minutesText.length() < 2) {
			minutesText = "0" + minutesText;
		}
		if (secondsText.length() < 2) {
			secondsText = "0" + secondsText;
		}

		String counterText = minutesText + ":" + secondsText;
		if (state == State.ZERO) {
			counterText = "STOP";
		}
		text.setText(counterText);

	}

	private Runnable mUpdateTimeTask = new Runnable() {

		public void run() {
			if (state == State.COUNTING) {
				counterSeconds -= speed;

				printCounter();
				postDelayed();

			}

		}
	};

	public boolean onKeyUp(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_CENTER:
			Log.e("tehis", "KEY CODE SOMWHERE00");
			return true;
		}
		return false;

	}

	@Override
	protected void onStop() {
		super.onStop();

		// Save user preferences. We need an Editor object to
		// make changes. All objects are from android.context.Context
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		
		editor.putInt("index", index);
		Log.e("data", "Save the index before ending app: " + index);
		editor.putInt("position", player.getDuration());
		Log.e("data", "Save current position as well " + player.getDuration());

		// Don't forget to commit your edits!!!
		editor.commit();
		Log.e("data", "Stopping app.. I will kill it!");
		kill();
		
		
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mHandler.removeCallbacks(mUpdateTimeTask);
		Log.e("data", "Pausing for some reaseon");
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	void kill() {
		this.finish();
	}


}